//
//  OYEmotionView.swift
//  weiboCopycat
//
//  Created by Orange Yu on 2016/12/10.
//  Copyright © 2016年 Orange Yu. All rights reserved.
//

import UIKit

let OYEmotionViewCellIdentifier = "OYEmotionViewCellIdentifire"
class OYEmotionView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    var flowLayout:UICollectionViewFlowLayout?
    
    
     // MARK: -控件懒加载
    /// 底部工具栏
    lazy var emotionToolBar:OYEmotionToolBar = {
        let emotionToolBar = OYEmotionToolBar()
        emotionToolBar.axis = .horizontal
        emotionToolBar.distribution = .fillEqually
        return emotionToolBar
    }()
    
    lazy var emotionList:[[[OYEmotionModel]]] = {
        
        let emotionList = OYEmotionTools.sharedTools.allEmotionArr
        return emotionList
        
    }()
    
    // 存放表情的CollectionView
    lazy var emotionCollectionView:UICollectionView = {
       
        let flowLayout = UICollectionViewFlowLayout()
        self.flowLayout = flowLayout
        
        let emotionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
        emotionView.dataSource = self
        emotionView.delegate = self
        
        emotionView.backgroundColor = UIColor.brown
        emotionView.register(OYEmotionViewCell.self, forCellWithReuseIdentifier: OYEmotionViewCellIdentifier)
        
        emotionView.isPagingEnabled = true
        emotionView.bounces = false
        emotionView.showsVerticalScrollIndicator = false
        emotionView.showsHorizontalScrollIndicator = false
        return emotionView
    }()
     /// 分页指示器
    private lazy var pageControl: UIPageControl = {
        let pageControl:UIPageControl = UIPageControl()
        pageControl.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
        pageControl.currentPageIndicatorTintColor = UIColor(patternImage:UIImage(named: "compose_keyboard_dot_selected")! )
        pageControl.numberOfPages = 5
        // MARK: -当只有一页的时候，取消pageControll
        pageControl.hidesForSinglePage = true
        return pageControl
    }()
    
     // MARK: -设置CollectionView的layout
    override func layoutSubviews() {
        super.layoutSubviews()
        
        self.flowLayout?.itemSize = CGSize(width: self.width, height: self.height - 35)
        self.flowLayout?.scrollDirection = .horizontal
        self.flowLayout?.minimumLineSpacing = 0
        self.flowLayout?.minimumInteritemSpacing = 0
        
    }
    
    /// 添加布局子控件
    func setupUI (){
        self.backgroundColor = UIColor.orange
        
        addSubview(emotionToolBar)
        addSubview(emotionCollectionView)
        addSubview(pageControl)
        
        emotionToolBar.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self)
            make.height.equalTo(35)
        }
        
        emotionCollectionView.snp_makeConstraints { (make) in
            make.left.right.top.equalTo(self)
            make.bottom.equalTo(emotionToolBar.snp_top)
        }
        
        pageControl.snp_makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.bottom.equalTo(emotionToolBar.snp_top).offset(10)
        }
        
         // MARK: -默认滚动到第二组(使用主线程异步，因为setupUI的时候CollectionView的数据还没有传过来)
        let originalIndexPath = IndexPath(item: 0, section: 1)
        DispatchQueue.main.async {
//            self.emotionCollectionView.scrollToItem(at: originalIndexPath, at: .right, animated: false)
            self.emotionCollectionView.selectItem(at: originalIndexPath, animated: false, scrollPosition: .left)
        }
                
         // MARK: -点击button的闭包，在这里设置点击button切换CollectionView的cell，以及设置pageControl的数据
        var currentIndexPath:IndexPath?
        emotionToolBar.closure = { (toolBatBtntype) -> Void in
            switch toolBatBtntype {
            case .recent:
                currentIndexPath = IndexPath(item: 0, section: 0)
            case .normal:
                currentIndexPath = IndexPath(item: 0, section: 1)
            case .emoji:
                currentIndexPath = IndexPath(item: 0, section: 2)
            case .lxh:
                currentIndexPath = IndexPath(item: 0, section: 3)
            }
            self.emotionCollectionView.scrollToItem(at: currentIndexPath!, at: .left, animated: false)
        }
        
    }

    func reloadRecentEmotionCell() {
        let indexPath = IndexPath(item: 0, section: 0)
        emotionCollectionView.reloadItems(at: [indexPath])
    }
    
    fileprivate func setPageControlData (indexPath:IndexPath) {
        pageControl.currentPage = indexPath.item
        pageControl.numberOfPages = emotionList[indexPath.section].count
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
}

 // MARK: -EmotionView的数据源方法
extension OYEmotionView:UICollectionViewDataSource,UICollectionViewDelegate {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return OYEmotionTools.sharedTools.allEmotionArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return OYEmotionTools.sharedTools.allEmotionArr[section].count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier:OYEmotionViewCellIdentifier, for: indexPath) as! OYEmotionViewCell
        cell.indexPath = indexPath
        cell.emotionModelList = OYEmotionTools.sharedTools.allEmotionArr[indexPath.section][indexPath.item]
        
        cell.backgroundColor = UIColor.white
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
         // MARK: -当滚动到每一组第一页或者最后一页的时候，将组号传递给toolBar，更改toolBar中button的选中状态
        if indexPath.item == 0 || indexPath.item == emotionList[indexPath.section].count - 1{
            emotionToolBar.selectButton(section: indexPath.section)
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
         // MARK: -根据监听的滚动设置pageControl
        let centerX = emotionCollectionView.width / 2 + emotionCollectionView.contentOffset.x
        let centerY = emotionCollectionView.height / 2
        let contentCenter = CGPoint(x: centerX, y: centerY)
        
        if let indexPath = emotionCollectionView.indexPathForItem(at: contentCenter) {
            setPageControlData(indexPath: indexPath)
        }
        
    }
}
